/**
 * 
 */
package com.angis.fx.activity.search;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.BounceInterpolator;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

import com.angis.fx.activity.R;
import com.angis.fx.activity.service.PicUploadService;
import com.angis.fx.adapter.ImageAdapter;
import com.angis.fx.data.ChangsuoInformation;
import com.angis.fx.data.PictureInfo;
import com.angis.fx.util.UploadUtil;
import com.angis.fx.util.ReadDirector;

/**
 * @author Han
 * 
 */
public class ChangsuoPictureActivity extends Activity {

	ImageView dialog_view;
	Spinner spinner;
	Button takeimagebutton;
	Button browseimagebutton;
	// Button uploadimagebutton;
	ImageAdapter adapter;
	private ImageView imageView;
	GridView imageGridView;
	List<Bitmap> list;
	String[] filelist;
	int l_position;
	private String upLoadPath;
	private PictureInfo pictureInfo =new PictureInfo();
	// private String pictype

	private String path = android.os.Environment.getExternalStorageDirectory() + "/fx/";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.changsuopicture);
		//pictureInfo = ;
		Bundle bundle = this.getIntent().getExtras();
		Object obj = bundle.get("selectedcs");
		if (obj != null) {
			ChangsuoInformation mChangsuoInfo = (ChangsuoInformation) obj;
			pictureInfo.setPictype("1");
			pictureInfo.setRecordid(mChangsuoInfo.getCsId());
		} else {
			pictureInfo.setPictype(bundle.getString("pictype"));
			pictureInfo.setRecordid(bundle.getString("recordid"));
			pictureInfo.setPicrecordid(bundle.getString("picrecordid"));
		}
		imageView = (ImageView) findViewById(R.id.changsuopictureimage);
		String csId = getIntent().getStringExtra("csid");
		takeimagebutton = (Button) findViewById(R.id.takeimagebutton);
		browseimagebutton = (Button) findViewById(R.id.browseimagebutton);
		// uploadimagebutton = (Button) findViewById(R.id.uploadimagebutton);
		imageGridView = (GridView) findViewById(R.id.gridview);
		imageGridView = (GridView) findViewById(R.id.imagegridview);

		imageView.setMaxHeight(1);
		setPath();
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// Toast.makeText(ChangsuoPictureActivity.this, position,
				// Toast.LENGTH_LONG).show();
				System.out.println(position);
				switch (position) {
				case 0:
					path = android.os.Environment.getExternalStorageDirectory()
							+ "/fx/";

					break;
				case 1:
					path = android.os.Environment.getExternalStorageDirectory()
							+ "/fx/upLoad/";
					break;
				default:
					break;
				}
				File lfile = new File(path);
				if (!lfile.exists()) {
					lfile.mkdirs();
				}

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});
		restartGridView();

		browseimagebutton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				clearBitMap();
				restartGridView();
			}
		});
		takeimagebutton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent lIntent = new Intent();
				lIntent.setClass(ChangsuoPictureActivity.this,
						CameraPicture.class);
				ChangsuoPictureActivity.this.startActivity(lIntent);
			}
		});

		imageGridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterView, View view,
					int position, long arg3) {
				try {
					l_position = position;
					dialog_view = new ImageView(ChangsuoPictureActivity.this);
					String[] t_s = getfilelist(path);
					upLoadPath = path + t_s[t_s.length - position - 1];
					Bitmap mBitmap = Bitmap.createScaledBitmap(BitmapFactory
							.decodeFile(upLoadPath), 300, 300, true);
					dialog_view.setImageBitmap(mBitmap);
					new AlertDialog.Builder(ChangsuoPictureActivity.this)
							.setIcon(R.drawable.icon)
							.setTitle("图片预览")
							.setView(dialog_view)
							.setNegativeButton(
									"取消",
									new android.content.DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {

										}
									})
							.setPositiveButton(
									"上传",
									new android.content.DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											
											Intent lIntent = new Intent(
													ChangsuoPictureActivity.this,
													PicUploadService.class);
											pictureInfo.setUpLoadPath(upLoadPath);
											lIntent.putExtra("picinfo", pictureInfo);
											ChangsuoPictureActivity.this.startService(lIntent);
											dialog.dismiss();
										}
									})
							.setNeutralButton(
									"删除",
									new android.content.DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											list.remove(list.get(l_position));
											String[] t_s = getfilelist(path);
											String t_filename = t_s[t_s.length
													- l_position - 1];
											File del = new File(path
													+ t_filename);
											del.delete();
											adapter.setImage(list
													.toArray(new Bitmap[list
															.size()]));
											imageGridView.invalidateViews();
										}
									}).show();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		// uploadimagebutton.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// ChangsuoPictureActivity.this.startService(new Intent(
		// ChangsuoPictureActivity.this, PicUploadService.class));
		// }
		// });
		// Button lSearchButton = (Button) findViewById(R.id.fieldsearchbutton);
		// lSearchButton.setOnClickListener(new OnClickListener() {
		//			
		// @Override
		// public void onClick(View v) {
		// Intent lIntent = new Intent();
		// lIntent.setClass(FieldSearchActivity.this,
		// BriefSearchResultActivity.class);
		// FieldSearchActivity.this.startActivity(lIntent);
		// }
		// });
	}

	private void setPath() {
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item);
		adapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		adapter.add("未保存图片");
		adapter.add("已保存图片");
		spinner = (Spinner) findViewById(R.id.changsuopicturepath);
		spinner.setAdapter(adapter);
	}

	@Override
	protected void onRestart() {

		if (CameraPicture.isShoot && CameraPicture.pbitmap != null
				&& !CameraPicture.pbitmap.isRecycled()) {
			// Toast.makeText(this, "restart", Toast.LENGTH_SHORT).show();
			clearBitMap();
			//Bitmap mBitmap = Bitmap.createScaledBitmap(CameraPicture.pbitmap, 64, 64, true);
			list = new ArrayList<Bitmap>();
			list.add(Bitmap.createScaledBitmap(CameraPicture.pbitmap, 64, 64, true));
			CameraPicture.pbitmap.recycle();
			this.adapter.setImage(list.toArray(new Bitmap[list.size()]));
			this.imageGridView.invalidateViews();
		} else {
			restartGridView();
		}
		super.onRestart();
	}

	private void clearBitMap() {
		for (Bitmap p : list) {
			if (!p.isRecycled()) {
				p.recycle();
			}
		}
	}

	private void restartGridView() {
		try {
			list = new ArrayList<Bitmap>();
			filelist = getfilelist(path);
			if (filelist != null && filelist.length>0) {
				for (int i = filelist.length - 1; i >= 0; i--) {
					// if (filelist.length - i > 9) {
					// break;
					// }
					Bitmap mBitmap = Bitmap.createScaledBitmap(BitmapFactory
							.decodeFile(new File(path + filelist[i]).getAbsolutePath()), 64, 64, true);
					list.add(mBitmap);
				}
			}

			if (adapter == null) {
				adapter = new ImageAdapter(list.toArray(new Bitmap[list.size()]),
						ChangsuoPictureActivity.this);
				imageGridView.setAdapter(adapter);
			} else {
				adapter.setImage(list.toArray(new Bitmap[list.size()]));
				imageGridView.invalidateViews();
			}
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(this, "预览图片加载失败", Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public void finish() {
		clearBitMap();
		super.finish();
	}

	private String[] getfilelist(String path) {
		// File file = new File(path);
		// if (file.isDirectory()) {
		// String[] filelist = file.list();
		//			
		// return filelist;
		// }
		try {
			List<String> filenames = ReadDirector.getFiles(path);
			return filenames.toArray(new String[filenames.size()]);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}
}
